package com.example.bicycle.mqtt;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.example.bicycle.domain.entity.Battery;
import com.example.bicycle.domain.entity.ElectricBike;
import com.example.bicycle.domain.mqtt.PublishSettingMessageVo;
import com.example.bicycle.domain.mqtt.ReceiveMessageVo;
import com.example.bicycle.service.BatteryService;
import com.example.bicycle.service.ElectricBikeService;
import com.example.bicycle.service.ReceiveMessageService;
import com.example.bicycle.utils.BeanCopyUtils;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import static com.example.bicycle.domain.enums.AppHttpCodeEnum.BIKE_SWITCH_OFF;
import static com.example.bicycle.domain.enums.AppHttpCodeEnum.BIKE_SWITCH_ON;
import static com.example.bicycle.mqtt.impl.MqttMessageServiceImpl.clientsStatusMap;

@Slf4j
@Component
public class InitCallback implements MqttCallback {
    private String messageContent;
    private BatteryService batteryService;
    private ElectricBikeService electricBikeService;
    private ReceiveMessageService receiveMessageService;

    private MqttMessageService mqttMessageService;

    @Autowired

    public InitCallback(BatteryService batteryService, ElectricBikeService electricBikeService, ReceiveMessageService receiveMessageService, MqttMessageService mqttMessageService) {
        this.batteryService = batteryService;
        this.electricBikeService = electricBikeService;
        this.receiveMessageService = receiveMessageService;
        this.mqttMessageService = mqttMessageService;
    }

    @Override
    public void connectionLost(Throwable cause) {
        System.out.println("connectionLost: " + cause.getMessage());
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) {
        System.out.println("topic: " + topic);
        System.out.println("Qos: " + message.getQos());
        messageContent = new String(message.getPayload());
        System.out.println("message content: " + messageContent);
        
        //在这调用Service方法
        //判断Topic进行
        if ("topic1".equals(topic)) {
            handleDataTopic();
        } else if (topic.contains("$SYS/brokers/") && topic.contains("/clients/")) {
            handleClientStatusTopic(topic);
        } else {
            log.info("收到未知主题消息: {}", topic);
        }
    }
    
    /**
     * 处理数据主题消息
     */
    private void handleDataTopic() {
        try{
            ReceiveMessageVo receiveMessageVo = JSON.parseObject(messageContent,ReceiveMessageVo.class);
            receiveMessageService.save(receiveMessageVo);
            ElectricBike temp = BeanCopyUtils.copyBean(receiveMessageVo, ElectricBike.class);
            ElectricBike electricBike = electricBikeService.getById(temp.getBikeId());

            if(receiveMessageVo.getIsLock()==0) {
                temp.setSwitchState(BIKE_SWITCH_ON.getCode());
            } else {
                temp.setSwitchState(BIKE_SWITCH_OFF.getCode());
            }
            if(electricBike!=null) {
                electricBike.copyAttributesFrom(temp);
                electricBikeService.updateById(electricBike);
            }else {
                electricBikeService.save(temp);
            }

            Battery temp2 = BeanCopyUtils.copyBean(receiveMessageVo, Battery.class);
            Battery battery = batteryService.getById(temp2.getBatteryId());
            /* 有id则更新无id则添加（添加逻辑没写） */
            if(battery!=null){
                battery.copyAttributesFrom(temp2);
                batteryService.updateById(battery);
            } else {
                batteryService.save(temp2);
            }

        } catch (JSONException e) {
            log.error("接收数据解析失败: {}", e.getMessage());
        }
    }
    
    /**
     * 处理客户端状态主题消息
     */
    private void handleClientStatusTopic(String topic) {
        try {
            log.info("收到客户端状态消息 - 主题: {}, 内容: {}", topic, messageContent);
            
            String clientId = null;
            
            // 尝试解析JSON格式的消息
            try {
                if (messageContent != null && !messageContent.trim().isEmpty() && messageContent.trim().startsWith("{")) {
                    JSONObject jsonObject = JSON.parseObject(messageContent);
                    clientId = jsonObject.getString("clientid");
                    if (clientId == null || clientId.isEmpty()) {
                        // 尝试其他可能的字段名
                        clientId = jsonObject.getString("client_id");
                    }
                    if (clientId == null || clientId.isEmpty()) {
                        clientId = jsonObject.getString("id");
                    }
                    log.debug("从JSON消息中解析到客户端ID: {}", clientId);
                }
            } catch (JSONException e) {
                log.debug("JSON解析失败，将尝试从主题中提取客户端ID: {}", e.getMessage());
            }
            
            // 如果JSON解析失败或没有找到clientId，从主题中提取clientId
            if (clientId == null || clientId.isEmpty()) {
                // EMQX系统主题格式: $SYS/brokers/{node}/clients/{clientid}/connected
                // 或者: $SYS/brokers/{node}/clients/{clientid}/disconnected
                String[] topicParts = topic.split("/");
                if (topicParts.length >= 5) {
                    clientId = topicParts[4]; // 获取clientId部分
                    log.debug("从主题中解析到客户端ID: {}", clientId);
                }
            }
            
            if (clientId != null && !clientId.isEmpty()) {
                if (topic.endsWith("/connected")) {
                    log.info("客户端已上线：{}", clientId);
                    if (!"Focus".equals(clientId)) {
                        clientsStatusMap.put(clientId, true);
                        mqttMessageService.sendOfflineMessage(clientId);
                    }
                } else if (topic.endsWith("/disconnected")) {
                    log.info("客户端已下线：{}", clientId);
                    clientsStatusMap.put(clientId, false);
                } else if (topic.contains("/sessions/") && topic.endsWith("/created")) {
                    log.info("客户端会话已创建：{}", clientId);
                    // 可以根据需要处理会话创建事件
                } else if (topic.contains("/sessions/") && topic.endsWith("/terminated")) {
                    log.info("客户端会话已终止：{}", clientId);
                    // 可以根据需要处理会话终止事件
                } else {
                    log.info("收到客户端事件 - 主题: {}, 客户端: {}", topic, clientId);
                }
            } else {
                log.warn("无法从主题或消息中提取客户端ID - 主题: {}, 消息: {}", topic, messageContent);
            }
            
        } catch (Exception e) {
            log.error("客户端状态消息处理失败 - 主题: {}, 消息: {}, 错误: {}", topic, messageContent, e.getMessage(), e);
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        System.out.println("deliveryComplete---------" + token.isComplete());
    }
}
